#!/bin/bash

# 攻击机端 - Linux权限维持远程部署脚本
# 使用方法: bash attacker_deploy.sh <target_ip> <username> [password]
# 执行位置: 攻击机上执行

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 检查参数
if [[ $# -lt 2 ]]; then
    echo -e "${RED}使用方法: $0 <target_ip> <username> [password]${NC}"
    echo -e "${YELLOW}示例: $0 192.168.1.100 root mypassword${NC}"
    echo -e "${YELLOW}示例: $0 192.168.1.100 ubuntu (使用SSH密钥)${NC}"
    exit 1
fi

TARGET_IP="$1"
USERNAME="$2"
PASSWORD="$3"

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║              攻击机端 - 权限维持远程部署工具                  ║${NC}"
echo -e "${BLUE}║              目标: $USERNAME@$TARGET_IP                      ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"

# 检查连通性
echo -e "${YELLOW}[1/4] 检查目标连通性...${NC}"
if ping -c 1 "$TARGET_IP" > /dev/null 2>&1; then
    echo -e "${GREEN}✓ 目标主机可达${NC}"
else
    echo -e "${RED}✗ 目标主机不可达${NC}"
    exit 1
fi

# 检查SSH连接
echo -e "${YELLOW}[2/4] 检查SSH连接...${NC}"
if [[ -n "$PASSWORD" ]]; then
    # 使用密码连接
    if command -v sshpass > /dev/null; then
        SSH_CMD="sshpass -p '$PASSWORD' ssh -o StrictHostKeyChecking=no"
        SCP_CMD="sshpass -p '$PASSWORD' scp -o StrictHostKeyChecking=no"
    else
        echo -e "${RED}✗ 需要安装sshpass工具: sudo apt-get install sshpass${NC}"
        exit 1
    fi
else
    # 使用SSH密钥连接
    SSH_CMD="ssh -o StrictHostKeyChecking=no"
    SCP_CMD="scp -o StrictHostKeyChecking=no"
fi

# 测试SSH连接
if $SSH_CMD "$USERNAME@$TARGET_IP" "echo 'SSH连接成功'" > /dev/null 2>&1; then
    echo -e "${GREEN}✓ SSH连接正常${NC}"
else
    echo -e "${RED}✗ SSH连接失败，请检查凭据${NC}"
    exit 1
fi

# 上传测试脚本
echo -e "${YELLOW}[3/4] 上传测试脚本到目标机器...${NC}"
SCRIPT_PATH="$(dirname "$0")/simple_test.sh"
if [[ ! -f "$SCRIPT_PATH" ]]; then
    echo -e "${RED}✗ 找不到simple_test.sh脚本${NC}"
    exit 1
fi

$SCP_CMD "$SCRIPT_PATH" "$USERNAME@$TARGET_IP:/tmp/simple_test.sh"
echo -e "${GREEN}✓ 脚本上传成功${NC}"

# 远程执行测试
echo -e "${YELLOW}[4/4] 在目标机器上执行权限维持测试...${NC}"
echo -e "${BLUE}════════════════ 目标机器执行输出 ════════════════${NC}"

$SSH_CMD "$USERNAME@$TARGET_IP" "sudo bash /tmp/simple_test.sh"

echo -e "${BLUE}════════════════ 执行完成 ════════════════${NC}"

# 下载测试报告
echo -e "${YELLOW}[下载] 获取测试报告...${NC}"
REPORT_FILE=$(date +%Y%m%d_%H%M%S)
$SCP_CMD "$USERNAME@$TARGET_IP:/tmp/persistence_test_report_*.txt" "./test_report_${TARGET_IP}_${REPORT_FILE}.txt" 2>/dev/null || echo -e "${YELLOW}⚠️  报告下载失败，请手动获取${NC}"

echo -e "\n${GREEN}🎉 远程部署和测试完成！${NC}"
echo -e "${BLUE}[提示] 要清理目标机器，请运行:${NC}"
echo -e "${BLUE}       $0 $TARGET_IP $USERNAME cleanup${NC}"

# 清理选项
if [[ "$4" == "cleanup" ]] || [[ "$3" == "cleanup" && -z "$PASSWORD" ]]; then
    echo -e "\n${YELLOW}[清理] 清理目标机器测试环境...${NC}"
    $SSH_CMD "$USERNAME@$TARGET_IP" "sudo bash /tmp/simple_test.sh cleanup"
    $SSH_CMD "$USERNAME@$TARGET_IP" "rm -f /tmp/simple_test.sh"
    echo -e "${GREEN}✓ 目标机器清理完成${NC}"
fi